package com.sun.baizhi.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQUtil {
   private static ConnectionFactory connectionFactory = new ConnectionFactory();

    /**
     * 获取连接
     * @param host 主机地址
     * @param port 端口
     * @param virtualHost  虚拟主机
     * @param userName      用户名
     * @param pas           密码
     */
    public static Connection getConnection(String host,Integer port,String virtualHost,String userName,String pas) throws IOException, TimeoutException {
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost(virtualHost);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(pas);
        return connectionFactory.newConnection();
    }

    /**
     * 关闭资源
     * @param connection  连接
     * @param channel  通道
     */
    public static void close(Connection connection, Channel channel){
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
